# -*- encoding: utf-8 -*-
import datetime, calendar
import math

from django.utils.html import escape

class Grapher:
    CHART_BASE_URL = u"http://chart.apis.google.com/chart?chs=700x250&"
    def __init__(self, title, dates, values):
        self.title = title
        self.chart_type = "lxy"
        self.min_value = 0
        self.max_value = None
        self.max_date = datetime.datetime.now()
        self.min_date = datetime.datetime.now() - datetime.timedelta(days=30)
        self.dates = dates
        self.values = values
        self.color = '&chco=0000ff'
        self.extra = ''
        self.display_data_func = lambda a: str(int(a))

        # for value not in base 10 (like time)
        self.unit_max = 10000
        self.unit_base = 10 

    def _get_max_value(self):
        if self.max_value:
            return self.max_value
        max_value = max(self.values)
        i = self.unit_max
        while(i>1):
            if max_value > i:
                div = i
                break
            i /= self.unit_base
        remainder = max_value % div
        return max_value + div - remainder

    def get_y_axis_labels(self, min, max):
        delta = int(max-min)
        for nb_div in xrange(10, 5, -1):
            if (delta % nb_div) == 0:
                break

        delta = float(max-min)/nb_div
        labels = []
        for i in xrange(nb_div+1):
            labels.append(self.display_data_func(min+i*delta))
        return '|'.join(labels)

    def get_x_axis_labels(self, min_date, max_date):
        i = min_date
        labels = []
        while(i<max_date):
            labels.append(i.strftime("%d/%m"))
            i+=datetime.timedelta(days=2)
        labels.append(i.strftime("%d/%m"))
        return '|'.join(labels)

    def get_chart_url(self):
        chart_global = "&cht=%s&chtt=%s" % (self.chart_type,escape(self.title))
        dates = [calendar.timegm(date.timetuple()) for date in self.dates]
        data = "&chd=t:%s|%s" % (",".join([str(date) for date in dates]), ",".join([str(value) for value in self.values]))
        max_value = self._get_max_value()
        data_scaling = "&chds=%s,%s,%s,%s" % (calendar.timegm(self.min_date.timetuple()),
                                              calendar.timegm(self.max_date.timetuple()),
                                              self.min_value, 
                                              max_value)
        y_axis_labels = self.get_y_axis_labels(self.min_value, max_value)
        x_axis_labels = self.get_x_axis_labels(self.min_date, self.max_date)
        axis = "&chxl=" + '0:|%s|' % x_axis_labels + '1:|%s|' % y_axis_labels + '2:|%s' % y_axis_labels
        axis_labels = "&chxt=x,y,r" + axis
        return self.CHART_BASE_URL + chart_global + data + data_scaling + axis_labels + self.color + self.extra

